<template>
  <view class="body">
    <view class="date_top">
      <view class="date_btn" @tap="showCalendar">
        <text class="date">{{ isToday(state.today) }}</text>
        <image
          class="img_arrow"
          v-if="!state.datepickShow"
          src="https://ainengli.hzjrsw.com/jkhx/common/arrow_down.png"
        />
        <image
          class="img_arrow"
          v-if="state.datepickShow"
          src="https://ainengli.hzjrsw.com/jkhx/common/arrow_up.png"
        />
      </view>
    </view>
    <up-popup :show="state.dateShow" :round="16" mode="bottom" @close="closeCalendar">
      <uni-calendar
        :date="formatDate(state.today, 'yyyy-MM-dd')"
        :showMonth="false"
        :selected="state.dateSelects"
        :start-date="formatDate(state.yearsAgo, 'yyyy-MM-dd')"
        :end-date="formatDate(state.now, 'yyyy-MM-dd')"
        @change="setDate"
        @monthSwitch="getMouthDate"
      />
    </up-popup>
    <!-- </uni-datetime-picker> -->
    <view class="seven">
      <view
        v-for="(item, index) in state.weekList"
        :key="index"
        :class="['items', index == state.active ? 'active' : '']"
        @tap="selectDate(item, index)"
        >{{ item.label }}</view
      >
    </view>
    <view class="today_food">
      <image
        class="img_record"
        v-if="isToday(state.today) == '今天'"
        src="https://ainengli.hzjrsw.com/jkhx/common/foodRecord.png"
      />
      <view class="circle_progress">
        <zui-progress-circle
          :position="0"
          :range="[270, 260]"
          :texture="['#00d1b6', '#f7f8fa']"
          :ringWidth="6"
          :size="120"
        />
        <view class="center_text">
          <view class="progress_num">{{ element.power.num }}</view>
          <view class="progress_has">已摄入千卡</view>
        </view>
      </view>
      <view class="element_list">
        <view class="element">
          <view class="title">
            <text class="title_name">碳水化合物</text>
            <text class="title_unit">g</text>
          </view>
          <progress
            :percent="element.carbon.percent"
            activeColor="#657EFF"
            :border-radius="100"
            stroke-width="4"
          />
          <view class="nums">{{ element.carbon.num.toFixed(2) }}</view>
        </view>
        <view class="element">
          <view class="title">
            <text class="title_name">蛋白质</text>
            <text class="title_unit">g</text>
          </view>
          <progress
            :percent="element.protein.percent"
            activeColor="#FF8450"
            :border-radius="100"
            stroke-width="4"
          />
          <view class="nums">{{ element.protein.num.toFixed(2) }}</view>
        </view>
        <view class="element">
          <view class="title">
            <text class="title_name">脂肪</text>
            <text class="title_unit">g</text>
          </view>
          <progress
            :percent="element.fat.percent"
            activeColor="#63A1FF"
            :border-radius="100"
            stroke-width="4"
          />
          <view class="nums">{{ element.fat.num.toFixed(2) }}</view>
        </view>
      </view>
    </view>
    <view v-if="mealInfo.length == 0" class="nodata">
      <image class="img_nodata" src="https://ainengli.hzjrsw.com/jkhx/noData.png" />
      <view class="nodata_text">还没有记录</view>
      <view class="nodata_text">请点击屏幕下方按钮来添加</view>
    </view>
    <!-- <view v-for="(i, idx) of tabList" :key="i">
      <view v-if="mealInfo[i]" class="meal_list">
        <view class="title">
          <text class="title_name">{{ i }}</text>
          <text class="title_power">已摄入{{ computeTotal((mealInfo[i] ? mealInfo[i] : [])) }}千卡</text>
        </view>
        <view class="meal_list_items">
          <view v-for="(item, index) of (mealInfo[i] ? mealInfo[i] : [])" :key="index" @tap="editFood(item, idx)" class="meal_list_item">
            <view class="name">{{ item.dietName }}</view>
            <view class="weight">{{ item.amount }}克</view>
            <view class="item_right">
              <view class="power">{{ item.energy }}千卡</view>
              <image class="img_more" src="https://ainengli.hzjrsw.com/jkhx/common/more.png" />
            </view>
          </view>
        </view>
      </view>
    </view> -->
    <view v-for="(i, idx) of mealInfo" :key="idx" class="meal_list">
      <view class="title">
        <text class="title_name">{{ i.dietType }}</text>
        <text class="title_power">已摄入{{ computeTotal(i.list) }}千卡</text>
      </view>
      <uni-swipe-action>
        <uni-swipe-action-item
          v-for="(item, index) of i.list"
          :key="index"
          :right-options="options"
          @click="handleClick(item)"
        >
          <view class="meal_list_items">
            <view @tap="editFood(item)" class="meal_list_item">
              <view class="name">{{ item.dietName }}</view>
              <view class="weight">{{ item.amount }}克</view>
              <view class="item_right">
                <view class="power">{{ ((item.amount * item.energy) / 100).toFixed(0) }}千卡</view>
                <image class="img_more" src="https://ainengli.hzjrsw.com/jkhx/common/more.png" />
              </view>
            </view>
          </view>
        </uni-swipe-action-item>
      </uni-swipe-action>
    </view>
    <!-- 食物重量设置 -->
    <up-popup :show="state.setShow" :round="16" mode="bottom" closeable @close="close">
      <view class="food_info">
        <view class="title">
          {{ editInfo.date + ' ' + editInfo.foodInfo.dietType }}
        </view>
        <view class="info_top">
          <view class="name">{{ editInfo.foodInfo.dietName }}</view>
          <view class="power">{{ editInfo.foodInfo.energy }}千卡/100克</view>
        </view>
        <view class="info_detail">
          <view class="detail_item">
            <view class="text">热量</view>
            <view
              >{{
                (editInfo.foodInfo.energy * (editInfo.foodInfo.amount / 100)).toFixed(1)
              }}千卡</view
            >
          </view>
          <view class="detail_item">
            <view class="text">碳水化合物</view>
            <view
              >{{ (editInfo.foodInfo.cho * (editInfo.foodInfo.amount / 100)).toFixed(1) }}克</view
            >
          </view>
          <view class="detail_item">
            <view class="text">蛋白质</view>
            <view
              >{{ (editInfo.foodInfo.pro * (editInfo.foodInfo.amount / 100)).toFixed(1) }}克</view
            >
          </view>
          <view class="detail_item">
            <view class="text">脂肪</view>
            <view
              >{{ (editInfo.foodInfo.fat * (editInfo.foodInfo.amount / 100)).toFixed(1) }}克</view
            >
          </view>
        </view>
        <view class="input_info">
          <input
            type="digit"
            class="weight_input"
            :focus="state.tipFocus"
            :adjustPosition="false"
            :maxlength="4"
            @input="onInput"
            @keyboardheightchange="onKey"
            v-model="editInfo.foodInfo.amount"
          />
          <view class="unit">克</view>
          <view class="hot"
            >(热量约{{
              (editInfo.foodInfo.energy * (editInfo.foodInfo.amount / 100)).toFixed(1)
            }}千卡)</view
          >
        </view>
        <button class="submit" @tap="setConfirm">确定</button>
        <view class="bottom_box" :style="{ height: `${state.bottomHeight}rpx` }" />
      </view>
    </up-popup>
    <!-- 底部导航 -->
    <view class="tabs">
      <view class="tab" @tap="setFood('早餐')">
        <icon type="" class="iconfont icon-zaocan1 img_tab" />
        <view class="tab-icon">
          <text
            type=""
            v-if="mealInfo.findIndex((item) => item.dietType === '早餐') != -1"
            class="iconfont icon-gouxuan img_finish"
          />
          <text v-else class="add">+</text>
          <text class="tab_text">早餐</text>
        </view>
      </view>
      <view class="tab" @tap="setFood('午餐')">
        <icon type="" class="iconfont icon-wufan img_tab" />
        <view class="tab-icon">
          <text
            type=""
            v-if="mealInfo.findIndex((item) => item.dietType === '午餐') != -1"
            class="iconfont icon-gouxuan img_finish"
          />
          <text v-else class="add">+</text>
          <text class="tab_text">午餐</text>
        </view>
      </view>
      <view class="tab" @tap="setFood('晚餐')">
        <icon type="" class="iconfont icon-wanfan1 img_tab" />
        <view class="tab-icon">
          <text
            type=""
            v-if="mealInfo.findIndex((item) => item.dietType === '晚餐') != -1"
            class="iconfont icon-gouxuan img_finish"
          />
          <text v-else class="add">+</text>
          <text class="tab_text">晚餐</text>
        </view>
      </view>
      <view class="tab" @tap="state.show = true">
        <icon type="" class="iconfont icon-jiacan1 img_tab" />
        <view class="tab-icon">
          <text class="add">+</text>
          <text class="tab_text">加餐</text>
        </view>
      </view>
    </view>
    <up-popup :show="state.show" :round="16" mode="bottom" @close="state.show = false">
      <view class="lists">
        <view @tap="setFood('早加餐')" class="item">早加餐</view>
        <view @tap="setFood('午加餐')" class="item">午加餐</view>
        <view @tap="setFood('晚加餐')" class="item">晚加餐</view>
      </view>
      <view class="cancel" @tap="cancel">取消</view>
    </up-popup>

    <!-- 补充信息 -->
    <up-popup
      :show="infoShow"
      :round="16"
      mode="bottom"
      @close="infoShow = false"
      :closeOnClickOverlay="false"
    >
      <view class="questionaire-info" v-if="questionList.length > 0">
        <view class="title"> 补充信息获取推荐摄入量 </view>
        <view class="questionaire-list">
          <view class="cell user-item">
            <view class="left">
              {{ state.userInfo.patientInfo.patName }}&nbsp;&nbsp;{{
                state.userInfo.patientInfo.gender
              }}&nbsp;&nbsp;{{ state.userInfo.patientInfo.age }}岁
            </view>
          </view>
          <view class="cell">
            <view class="left">身高</view>
            <view class="right">
              <input
                class="form_input"
                type="digit"
                @blur="heightfixed"
                v-model="baseInfo.height"
                placeholder="请输入"
                :border="false"
              />
              <text>cm</text>
            </view>
          </view>
          <view class="cell">
            <view class="left">当前体重</view>
            <view class="right">
              <input
                class="form_input"
                type="digit"
                @blur="weightfixed"
                v-model="baseInfo.weight"
                placeholder="请输入"
                :border="false"
              />
              <text>kg</text>
            </view>
          </view>
          <view class="topic_title">
            {{ questionList[0].list[2]?.questionName }}
            <view v-if="bmi < 24" class="tag needlose">您的体重未超标，不需要减重</view>
          </view>
          <view class="topics">
            <view
              v-for="(item, index) of questionList[0].list[2].options"
              :key="index"
              :class="[
                'topic',
                questionList[0].list[2].option.includes(item.id) ? 'active' : '',
                bmi < 24 ? 'disabled' : ''
              ]"
              @tap="answerSelect(item, 0)"
              >{{ item.label }}</view
            >
          </view>
          <view v-for="(vo, voIndex) of questionList" :key="voIndex">
            <view v-if="voIndex > 0 && voIndex < questionList.length - 1">
              <view class="topic_title">
                {{ vo.list[0]?.questionName }}
                <view v-if="vo.list[0].questionType == '多选'" class="tag">多选</view>
              </view>
              <view class="topics">
                <view
                  v-for="(item, index) of vo.list[0].options"
                  :key="index"
                  :class="['topic', vo.list[0].option.includes(item.id) ? 'active' : '']"
                  @tap="answerSelect(item, voIndex)"
                  >{{ item.label }}</view
                >
              </view>
            </view>
            <view v-if="voIndex == questionList.length - 1">
              <view class="topic_title">
                {{ vo.list[0]?.questionName }}
                <view class="tag">{{ vo.list[0]?.questionType }}</view>
              </view>
              <view @tap="searchShow = true" class="search-input">
                <up-icon name="search" color="#000" size="28" />
                搜索过敏和禁忌食物
              </view>
              <view class="allergy-foods">
                <view class="food-list">
                  <view
                    v-for="(item, index) of state.searchResults"
                    :key="index"
                    class="foods-item"
                  >
                    {{ item }}
                    <text @tap="removeFood(item)" style="padding: 0 4rpx; font-size: 36rpx">×</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="submit-box">
          <view class="submit-btn" @tap="submit">提交</view>
        </view>
      </view>
    </up-popup>

    <up-popup :show="searchShow" mode="bottom" :round="16" closeable @close="searchShow = false">
      <view class="search-body">
        <view class="title">搜索并选择</view>
        <uni-search-bar
          v-model="state.searchValue"
          @cancel="cancelSearch"
          @focus="state.searchFocus = true"
          @input="searchFood"
          @clear="
            () => {
              state.isSearch = false
              state.searchList = []
            }
          "
          cancelButton="always"
          placeholder="搜索过敏和禁忌食物"
        />
        <!-- 搜索内容 -->
        <view v-if="state.searchFocus" class="search_content">
          <view v-if="state.searchHistory.length > 0 && !state.isSearch" class="search_history">
            <view class="history_top">
              <view class="title">搜索记录</view>
              <icon type="" @tap="clearSearchHistory" class="iconfont icon-shanchu1 img_del" />
            </view>
            <view class="history_content">
              <view
                class="history_item"
                v-for="(item, index) in state.searchHistory"
                :key="index"
                @tap="historySelect(item)"
              >
                {{ item }}
              </view>
            </view>
          </view>
          <view v-if="state.searchList.length === 0 && state.isSearch" class="nodata">
            <image class="img_nodata" src="https://ainengli.hzjrsw.com/jkhx/noSearchData.png" />
            <view class="nodata_text">暂无数据，换个搜索条件试试?</view>
          </view>
          <view class="search_list">
            <view
              class="search_item"
              v-for="(item, index) in state.searchList"
              :key="index"
              @tap="selectFoods(item)"
            >
              <view class="name">{{ item.dietName }}</view>
              <image
                v-if="item.checked"
                class="img_right"
                src="https://ainengli.hzjrsw.com/jkhx/common/checkbox-active.png"
              />
              <image
                v-if="!item.checked"
                class="img_right"
                src="https://ainengli.hzjrsw.com/jkhx/common/checkbox.png"
              />
            </view>
          </view>
        </view>
        <view class="fixed">
          <button @tap="searchConfirm" class="confirm-btn popbtn">确定</button>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup lang="ts">
import { reactive, ref, computed } from 'vue'
import { formatDate } from '@/utils/util'
import { throttle, deepCopy, debounce } from '@/utils/tools'
import { onLoad, onShow } from '@dcloudio/uni-app'
import ZuiProgressCircle from '@/module/common/zui-progress-circle/zui-progress-circle.vue'
import {
  query_get_food,
  update_food,
  delete_food,
  query_mouth_food,
  search_food
} from '@/module/api/food'
import { weight_info_question, weight_save } from '@/module/api/questionaire'
import store from '@/store'

const state = reactive({
  now: new Date(),
  yearsAgo: new Date().setFullYear(new Date().getFullYear() - 1),
  today: new Date(),
  datepickShow: false,
  dateShow: false,
  dateSelects: [],
  show: false,
  setShow: false,
  userInfo: {},
  active: 0,
  weekList: [],
  tipFocus: false,
  bottomHeight: 0,
  searchFocus: false,
  isSearch: false,
  searchValue: '',
  searchHistory: [],
  searchList: [],
  searchResults: []
})

const baseInfo = ref({
  height: '',
  weight: ''
})
const questionList = ref([])
const questionInfo = ref()

const options = reactive([
  {
    text: '删除',
    style: {
      backgroundColor: '#ff503d'
    }
  }
])
const mealInfo = ref([])
const editInfo = reactive({
  date: '',
  type: '',
  foodInfo: {}
})
const element = reactive({
  power: {
    num: 0,
    percent: 1.1
  },
  carbon: {
    num: 0,
    percent: 100
  },
  protein: {
    num: 0,
    percent: 100
  },
  fat: {
    num: 0,
    percent: 100
  }
})

const infoShow = ref<boolean>(false)
const disabledFood = ref('')
const searchShow = ref(false)
const bmi = computed(() => {
  if (baseInfo.value.weight && baseInfo.value.height) {
    return (
      baseInfo.value.weight / ((baseInfo.value.height / 100) * (baseInfo.value.height / 100)) || 0
    )
  } else {
    return 25
  }
})

let currentId = ''
onShow(() => {
  state.userInfo = uni.getStorageSync('userInfo') ? JSON.parse(uni.getStorageSync('userInfo')) : {}
  currentId = deepCopy(state.userInfo.patientInfo.empi)
  state.show = false // 加餐成功返回关闭加餐弹窗
  getTime()
  getData()
  const currentMouth = {
    year: new Date().getFullYear(),
    month: new Date().getMonth() + 1
  }
  getMouthDate(currentMouth)

  if (!state.userInfo.patientInfo.dietQuestionState) {
    infoShow.value = true

    weight_info_question({ id: 1 }).then((res) => {
      if (res.data.content) {
        const stringData = JSON.parse(res.data.content)
        questionInfo.value = res.data
        questionList.value = stringData.map((item: any) => {
          item.list.forEach((val: any) => {
            val.option = ''
            val.scores = ''
          })

          return item
        })
      }
    })
  }
})

const showCalendar = () => {
  state.datepickShow = !state.datepickShow
  state.dateShow = !state.dateShow
}
const closeCalendar = () => {
  state.dateShow = false
  state.datepickShow = false
}

const getData = () => {
  const params = {
    empi: state.userInfo.patientInfo.empi,
    date: formatDate(state.today, 'yyyy-MM-dd')
  }
  query_get_food(params).then((res) => {
    mealInfo.value = res.data
    // 计算今日饮食总能量
    element.power.num = 0
    element.carbon.num = 0
    element.protein.num = 0
    element.fat.num = 0
    res.data.forEach((i) => {
      element.power.num += computeTotal(i.list)
      element.carbon.num += computeElement(i.list, 'cho')
      element.protein.num += computeElement(i.list, 'pro')
      element.fat.num += computeElement(i.list, 'fat')
    })
  })
}
const getMouthDate = (e) => {
  e.month = Number(e.month)
  const mouthStart =
    (e.month == 1 ? e.year - 1 : e.year) + '/' + (e.month == 1 ? 12 : e.month - 1) + '/20'
  const mouthEnd =
    (e.month == 12 ? e.year + 1 : e.year) + '/' + (e.month == 12 ? 1 : e.month + 1) + '/15'
  const params = {
    empi: state.userInfo.patientInfo.empi,
    start: formatDate(new Date(mouthStart), 'yyyy-MM-dd hh:mm:ss'),
    end: formatDate(new Date(mouthEnd), 'yyyy-MM-dd hh:mm:ss')
  }
  query_mouth_food(params).then((res) => {
    if (res.data && res.data.length > 0) {
      res.data.forEach((item) => {
        item.date = item.dietDate
        item.info = ''
      })
      state.dateSelects = res.data
    }
  })
}
const computeTotal = (arr: Array) => {
  // 计算热量
  let total = 0
  arr.forEach((item) => {
    total += Math.round((item.energy * item.amount) / 100)
  })
  return total
}
const computeElement = (arr: Array, type: string) => {
  // 计算营养素综合
  let total = 0
  arr.forEach((item) => {
    total += (item[type] * item.amount) / 100
  })
  return total
}

const getTime = () => {
  const day = state.today.getDay() === 0 ? 7 : state.today.getDay()
  state.weekList = getWeekDates()
  console.log(state.weekList, day)
  state.active = Number(day) - 1
  // state.weekList.forEach((item, index) => {
  //   if (day === 0) {
  //     state.active = 6
  //   }
  //   if (day == item) {
  //     state.active = index
  //   }
  // })
}

const getWeekDates = () => {
  const weekStringList = ['一', '二', '三', '四', '五', '六', '日']
  const now = state.today // 当前日期
  const currentDay = now.getDay() // 当前是周几（0 表示周日）
  const weekStart = new Date(now) // 当前周的第一天
  const weekDates: any = [] // 存储本周日期

  // 将周日调整为第 7 天（以周一为起始日）
  const adjustedDay = currentDay === 0 ? 7 : currentDay

  // 设置为本周周一
  weekStart.setDate(now.getDate() - adjustedDay + 1)

  for (let i = 0; i < 7; i++) {
    const weekDay = new Date(weekStart)
    weekDay.setDate(weekStart.getDate() + i)
    const formattedDate = `${weekDay.getFullYear()}-${(weekDay.getMonth() + 1)
      .toString()
      .padStart(2, '0')}-${weekDay.getDate().toString().padStart(2, '0')}`
    weekDates.push({ date: formattedDate, label: weekStringList[i] })
  }

  return weekDates
}

const selectDate = (data: any, index: number) => {
  state.active = index
  state.today = new Date(data.date)
  getData()
}
// const transformChinese = (item, index) => {
//   switch (item) {
//     case 1:
//       return '一'
//     case 2:
//       return '二'
//     case 3:
//       return '三'
//     case 4:
//       return '四'
//     case 5:
//       return '五'
//     case 6:
//       return '六'
//     case 7:
//       return '日'
//     default:
//       return ''
//   }
// }
const isToday = (val) => {
  // 今天昨天前天转换
  const select = formatDate(val, 'yyyy/MM/dd') + ' 00:00:00'
  const today = formatDate(state.now, 'yyyy/MM/dd') + ' 00:00:00'
  if (new Date(today).getTime() - new Date(select).getTime() == 0) {
    return '今天'
  } else if (new Date(today).getTime() - new Date(select).getTime() == 86400000) {
    return '昨天'
  } else if (new Date(today).getTime() - new Date(select).getTime() == 172800000) {
    return '前天'
  } else {
    return formatDate(val, 'yyyy.MM.dd')
  }
}
const setDate = (e) => {
  state.datepickShow = false
  state.dateShow = false
  state.today = new Date(e.fulldate)
  getTime()
  getData()
}
const editFood = (val: any) => {
  const now = new Date(state.today)
  const date = now.getMonth() + 1 + '月' + now.getDate() + '日'
  editInfo.date = date
  editInfo.type = val.dietType
  editInfo.foodInfo = deepCopy(val)
  state.setShow = true
  setTimeout(() => {
    // 解决弹窗打开时，input无法获取焦点问题
    state.tipFocus = true
  }, 100)
}
const setConfirm = () => {
  if (!editInfo.foodInfo.amount || editInfo.foodInfo.amount == '0') {
    uni.showToast({
      title: '重量不能为0或空!',
      icon: 'error'
    })
    return
  }
  editInfo.foodInfo.dietDate = formatDate(new Date(), 'yyyy-MM-dd')
  editInfo.foodInfo.amount = Number(editInfo.foodInfo.amount)
  update_food(editInfo.foodInfo).then((res) => {
    uni.showToast({
      title: '修改成功'
    })
    state.setShow = false
    state.tipFocus = false
    getData()
  })
}
const handleClick = (item: any) => {
  // 删除食物
  uni.showLoading()
  delete_food(item.id).then((res) => {
    uni.showToast({
      title: '删除成功'
    })
    uni.hideLoading()
    getData()
  })
}
const setFood = (val: string) => {
  uni.navigateTo({
    url:
      '/module/src/pages/food/dailyFood/detail?food=' +
      val +
      '&date=' +
      formatDate(state.today, 'yyyy-MM-dd')
  })
}
const onKey = (e) => {
  const sys = uni.getSystemInfoSync()
  // 弹出键盘事件
  if (e.detail.height) {
    state.bottomHeight = e.detail.height * 2 - sys.safeAreaInsets.bottom * 2 - 36
  } else {
    state.bottomHeight = 0
  }
}
const onInput = (e) => {
  if (e.detail.value * 1 > 3000) {
    editInfo.foodInfo.amount = 3000
  }
}

const close = () => {
  state.setShow = false
  state.tipFocus = false
  state.bottomHeight = 0
}

const cancel = () => {
  state.show = false
}

const heightfixed = (val: any) => {
  const textArr = val.target.value.split('.')
  if (textArr.length > 1 && textArr[1].length > 1) {
    baseInfo.value.height = Number(textArr[0] + '.' + textArr[1]).toFixed(1)
  }
  if (Number(baseInfo.value.height) > 250) {
    baseInfo.value.height = '250'
  }
}
const weightfixed = (val: any) => {
  const textArr = val.target.value.split('.')
  if (textArr.length > 1 && textArr[1].length > 1) {
    baseInfo.value.weight = Number(textArr[0] + '.' + textArr[1]).toFixed(1)
  }
  if (Number(baseInfo.value.weight) > 200) {
    baseInfo.value.weight = '200'
  }
}

const answerSelect = throttle((item: any, index: any) => {
  let currentQuestion = {}
  if (!index) {
    if (bmi.value < 24) {
      return
    }

    currentQuestion = questionList.value[index].list[2]
  } else {
    currentQuestion = questionList.value[index].list[0]
  }

  if (currentQuestion.questionType == '单选') {
    currentQuestion.value = item.value
    currentQuestion.option = item.id.toString()
    currentQuestion.scores = item.score
  } else {
    // 多选情况
    if (!currentQuestion.value || currentQuestion.value.length == 0) {
      currentQuestion.value = item.value
      currentQuestion.option = item.id.toString()
      currentQuestion.scores = item.score
    } else {
      // 多次选中
      if (!currentQuestion.option.includes(item.id)) {
        if (item.value == '以上都没有' || currentQuestion.value.includes('以上都没有')) {
          currentQuestion.value = item.value
          currentQuestion.option = item.id.toString()
          currentQuestion.scores = item.score
          currentQuestion.options.forEach((v: any) => {
            v.check = false
          })
        } else {
          currentQuestion.value = currentQuestion.value + ',' + item.value
          currentQuestion.option = currentQuestion.option + ',' + item.id
          currentQuestion.scores += item.score
        }
      } else {
        currentQuestion.value = currentQuestion.value.replace(item.value + ',', '')
        currentQuestion.value = currentQuestion.value.replace(',' + item.value, '')
        currentQuestion.value = currentQuestion.value.replace(item.value, '')
        currentQuestion.option = currentQuestion.option.replace(item.id + ',', '')
        currentQuestion.option = currentQuestion.option.replace(',' + item.id, '')
        currentQuestion.option = currentQuestion.option.replace(item.id, '')
        currentQuestion.scores -= item.score
      }
    }
  }
}, 300)

const cancelSearch = () => {
  state.searchFocus = false
  state.isSearch = false
  state.searchList = []
}
const clearSearchHistory = () => {
  state.searchHistory = []
  uni.removeStorageSync('searchHistory')
}
const searchFood = debounce((e) => {
  if (e == '') {
    state.isSearch = false
    state.searchList = []
    return
  }
  state.isSearch = true
  search_food(state.searchValue).then((res) => {
    state.searchList = res.data
    state.searchList.forEach((item) => {
      // 如果已选中的列表没有为false, 有就为true
      item.checked = false
      state.searchResults.forEach((i) => {
        if (i == item.dietName) {
          item.checked = true
        }
      })
    })
    // 保存搜索历史记录
    if (state.searchHistory.indexOf(e) == -1) {
      if (state.searchHistory.length >= 10) {
        state.searchHistory.pop()
      }
      state.searchHistory.unshift(e)
    }
    uni.setStorageSync('searchHistory', JSON.stringify(state.searchHistory))
  })
}, 1000)
const historySelect = (val: string) => {
  state.searchValue = val
  searchFood(state.searchValue)
}
const selectFoods = (item: any) => {
  if (!item.checked) {
    item.checked = true
    if (state.searchResults.includes(item.dietName)) {
      state.searchResults = state.searchResults.filter((name: string) => name != item.dietName)
    } else {
      state.searchResults.push(item.dietName)
    }
  } else {
    item.checked = false
    state.searchResults = state.searchResults.filter((name: string) => name != item.dietName)
  }
}
const removeFood = (item: string) => {
  state.searchResults = state.searchResults.filter((name: string) => name != item)
}
const searchConfirm = () => {
  searchShow.value = false
  state.searchValue = ''
  state.searchFocus = false
  state.isSearch = false
  state.searchList = []
  disabledFood.value = state.searchResults.join(',')
}

// 补充问卷提交
const submit = () => {
  console.log(questionList.value)
  try {
    questionList.value.forEach((vo, index) => {
      if (index === 0) {
        const regex = /\..*\./
        const result1 = regex.test(String(baseInfo.value.weight))
        const result2 = regex.test(String(baseInfo.value.height))
        if (result1 || result2) {
          uni.showToast({
            title: '身高体重格式错误，请输入正确格式',
            icon: 'none'
          })
          throw Error()
        } else if (
          !baseInfo.value.weight ||
          !baseInfo.value.height ||
          (bmi.value > 24 && !vo.list[2].value)
        ) {
          uni.showToast({
            title: '请完成问卷填写！',
            icon: 'none'
          })
          throw Error()
        }
      } else if (index != questionList.value.length - 1) {
        if (vo.list[0].value == '') {
          uni.showToast({
            title: '请完成问卷填写！',
            icon: 'none'
          })
          throw Error()
        }
      } else {
        confirm()
      }
    })
  } catch {
    return
  }
}

const confirm = () => {
  // 给身高体重赋值
  questionList.value[0].list[0].inputText = baseInfo.value.height
  questionList.value[0].list[1].inputText = baseInfo.value.weight
  if (bmi.value < 24) {
    questionList.value[0].list[2].content = ''
  }
  const params = {
    clientId: 1,
    patientQuestionnaireAnswerVOs: []
  }
  questionList.value.forEach((item: any) => {
    item.list.forEach((val: any) => {
      const answerModel = {
        id: questionInfo.value.id,
        userId: state.userInfo.userId,
        empi: currentId,
        creator: '',
        createTime: questionInfo.value.createTime,
        updateTime: formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss'),
        questionnaireId: questionInfo.value.questionnaireId,
        questionId: val.id,
        questionnaireRecordId: questionInfo.value.questionnaireId,
        optionId: '',
        content: '',
        extContent: val.questionType == '选择 + 输入' ? val.inputText : '',
        score: val.scores
      }
      if (val.questionType == '单选' || val.questionType == '输入') {
        const answer = {
          ...answerModel,
          optionId: val.questionType == '单选' ? val.option : '',
          content: val.questionType == '输入' ? val.inputText : val.value
        }
        params.patientQuestionnaireAnswerVOs.push(answer)
      } else if (val.questionType == '多选') {
        const arr1 = val.value.split(',')
        const arr2 = val.option.split(',')
        arr1.forEach((i: string, idx: number) => {
          const answer = {
            ...answerModel,
            optionId: arr2[idx],
            content: i
          }
          params.patientQuestionnaireAnswerVOs.push(answer)
        })
      } else {
        state.searchResults.forEach((v: any) => {
          const answer = {
            ...answerModel,
            content: v
          }
          params.patientQuestionnaireAnswerVOs.push(answer)
        })
      }
    })
  })
  console.log(params)
  // uni.showLoading({
  //   title: '正在提交中...',
  //   mask: true
  // })
  // weight_save(params).then((res) => {
  //   if (res.code == 0) {
  //     state.userInfo.patientInfo.dietQuestionState = true
  //     store.commit('SET_USERINFO', state.userInfo)
  //     uni.hideLoading()

  //     getData()
  //     const currentMouth = {
  //       year: new Date().getFullYear(),
  //       month: new Date().getMonth() + 1
  //     }
  //     getMouthDate(currentMouth)
  //   }
  // })
}
</script>

<style lang="scss" scoped>
.body {
  padding: 0 32rpx;
  padding-bottom: calc(156rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(156rpx + env(safe-area-inset-bottom));

  .date_top {
    text-align: center;

    .date_btn {
      box-sizing: border-box;
      display: inline-block;
      height: 60rpx;
      padding: 0 32rpx;
      margin: 24rpx auto;
      line-height: 60rpx;
      text-align: center;
      background: #fff;
      border-radius: 38rpx;

      .date {
        font-size: 28rpx;
        font-weight: 400;
        color: #222;
      }

      .img_arrow {
        width: 24rpx;
        height: 24rpx;
        margin-left: 16rpx;
      }
    }
  }

  .seven {
    display: flex;
    gap: 24rpx;
    justify-content: space-between;
    margin-bottom: 26rpx;

    .items {
      box-sizing: border-box;
      width: 77rpx;
      height: 76rpx;
      font-size: 28rpx;
      font-weight: 400;
      line-height: 76rpx;
      color: #222;
      text-align: center;
      background: #fff;
      border-radius: 12rpx;
    }

    .active {
      color: #fff;
      background: #00d1b6;
    }
  }

  .today_food {
    position: relative;
    box-sizing: border-box;
    width: 686rpx;
    height: 428rpx;
    padding: 32rpx;
    background: #fff;
    border-radius: 16rpx;

    .img_record {
      position: absolute;
      top: 0;
      left: 0;
      width: 192rpx;
      height: 44rpx;
    }

    .circle_progress {
      width: 100%;
      height: 240rpx;
      margin-bottom: 24rpx;

      .center_text {
        margin-top: -170rpx;
        text-align: center;

        .progress_num {
          margin-bottom: 8rpx;
          font-size: 48rpx;
          font-weight: 600;
          color: #222;
        }

        .progress_has {
          font-size: 24rpx;
          font-weight: 400;
          color: #666;
        }
      }
    }

    .element_list {
      display: flex;
      justify-content: space-between;
    }

    .element {
      width: 26%;

      .title {
        display: flex;
        justify-content: space-between;
        margin-bottom: 16rpx;

        .title_name {
          font-size: 28rpx;
          font-weight: 400;
          color: #222;
        }

        .title_unit {
          font-size: 24rpx;
          font-weight: 400;
          color: #999;
        }
      }

      .nums {
        margin-top: 16rpx;
        font-size: 24rpx;
        font-weight: 400;
        color: #999;
      }
    }
  }

  .nodata {
    text-align: center;

    .img_nodata {
      width: 320rpx;
      height: 240rpx;
      margin-top: 60rpx;
    }

    .nodata_text {
      font-size: 28rpx;
      font-weight: 400;
      color: #666;
    }
  }

  .meal_list {
    padding: 32rpx;
    margin-top: 24rpx;
    background: #fff;
    border-radius: 16rpx;

    .title {
      display: flex;
      align-items: center;

      .title_name {
        font-size: 32rpx;
        font-weight: 500;
        color: #333;
      }

      .title_power {
        margin-left: 16rpx;
        font-size: 22rpx;
        font-weight: 400;
        color: #999;
      }
    }

    .meal_list_items {
      ::v-deep .uni-swipe {
        margin-top: 24rpx;
      }

      ::v-deep .uni-swipe_button {
        font-size: 24rpx;
        font-weight: 400;
        color: #fff;
        border-radius: 0 12rpx 12rpx 0 !important;
      }

      .meal_list_item {
        position: relative;
        box-sizing: border-box;
        padding-bottom: 24rpx;
        margin-top: 24rpx;
        border-bottom: 1px solid #e5e6eb;

        .name {
          margin-bottom: 10rpx;
          font-size: 30rpx;
          font-weight: 500;
          color: #333;
        }

        .weight {
          font-size: 28rpx;
          font-weight: 400;
          color: #999;
        }

        .power {
          margin-right: 16rpx;
          font-size: 24rpx;
          font-weight: 400;
          color: #999;
        }

        .item_right {
          position: absolute;
          top: 20rpx;
          right: 0;
          display: flex;

          .img_more {
            width: 32rpx;
            height: 32rpx;
          }
        }

        &:last-child {
          padding-bottom: 0;
          border: none;
        }
      }
    }
  }

  .tabs {
    position: fixed;
    bottom: 0;
    left: 0;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    width: 100%;
    padding: 16rpx 64rpx;
    padding-bottom: calc(30rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(30rpx + env(safe-area-inset-bottom));
    background: #fff;
    border-top: 1rpx solid #e5e6eb;

    .tab {
      .img_tab {
        margin-bottom: -8rpx;
        font-size: 48rpx;
        width: 48rpx;
        height: 48rpx;
      }

      .add {
        font-size: 20rpx;
        font-weight: 400;
        color: #666;
      }

      .img_finish {
        margin-right: 2rpx;
        font-size: 20rpx;
        width: 20rpx;
        height: 20rpx;
      }

      .tab_text {
        font-size: 20rpx;
        font-weight: 400;
        color: #666;
      }
    }
  }

  .fixed {
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 10;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    padding: 24rpx 32rpx;
    padding-bottom: calc(24rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
    background: #fff;
    border: 1rpx solid #e5e6eb;

    .pre-btn {
      width: 35%;
      font-size: 32rpx;
      font-weight: 700;
      color: #00d1b6;
      background: #fff;
      border: 1rpx solid #00d1b6;
      border-radius: 44rpx;
    }

    .confirm-btn {
      width: 60%;
      font-size: 32rpx;
      font-weight: 700;
      color: #fff;
      background: #00d1b6;
      border-radius: 44rpx;

      .img-logo {
        width: 32rpx;
        height: 32rpx;
        transform: translateY(4rpx);
      }
    }
  }

  .search-body {
    // 搜索弹窗
    width: 100vw;
    height: calc(100vh - 160rpx);

    .title {
      height: 108rpx;
      font-size: 32rpx;
      font-weight: 700;
      line-height: 108rpx;
      color: #222;
      text-align: center;
      border-bottom: 1rpx solid #e5e6eb;
    }

    .search_content {
      height: calc(100vh - 596rpx);
      background: #fff;

      .search_history {
        margin: 0 32rpx;

        .history_top {
          display: flex;
          justify-content: space-between;
          margin-bottom: 20rpx;

          .title {
            font-size: 30rpx;
            font-weight: 700;
            color: #333;
          }

          .img_del {
            width: 40rpx;
            height: 40rpx;
            font-size: 40rpx;
            color: #999;
          }
        }

        .history_content {
          display: flex;
          flex-wrap: wrap;
          gap: 20rpx;
          justify-content: flex-start;

          .history_item {
            padding: 10rpx 30rpx;
            font-size: 26rpx;
            font-weight: 400;
            color: #666;
            background: #fafafa;
            border-radius: 30rpx;
          }
        }
      }

      .nodata {
        text-align: center;

        .img_nodata {
          width: 320rpx;
          height: 240rpx;
          margin-top: 222rpx;
        }

        .nodata_text {
          font-size: 28rpx;
          font-weight: 400;
          color: #666;
        }
      }

      .search_list {
        height: calc(100vh - 524rpx);
        overflow: auto;
        background: #fff;

        .search_item {
          position: relative;
          box-sizing: border-box;
          height: 108rpx;
          padding: 34rpx 32rpx;
          border-bottom: 1rpx solid #e5e6eb;

          .name {
            font-size: 30rpx;
            font-weight: 500;
            color: #222;
          }

          .img_right {
            position: absolute;
            top: 50%;
            right: 32rpx;
            width: 40rpx;
            height: 40rpx;
            margin-top: -20rpx;
          }
        }
      }
    }

    .popbtn {
      width: 100%;
    }
  }

  ::v-deep .u-popup {
    .u-popup__content {
      overflow: hidden;
      // 设置重量弹窗
      .food_info {
        padding: 0 32rpx;

        .title {
          width: 100%;
          height: 104rpx;
          font-size: 30rpx;
          font-weight: 500;
          line-height: 104rpx;
          color: #333;
          text-align: center;
        }

        .info_top {
          .name {
            margin-bottom: 10rpx;
            font-size: 30rpx;
            font-weight: 500;
            color: #222;
          }

          .power {
            font-size: 28rpx;
            font-weight: 400;
            color: #666;
          }
        }

        .info_detail {
          box-sizing: border-box;
          display: flex;
          justify-content: space-between;
          padding: 20rpx 38rpx;
          margin: 26rpx 0 30rpx;
          font-size: 24rpx;
          font-weight: 400;
          color: #999;
          border-top: 1rpx solid #e5e6eb;
          border-bottom: 1rpx solid #e5e6eb;

          .detail_item {
            flex: 1;
            text-align: center;

            .text {
              margin-bottom: 10rpx;
            }
          }
        }

        .input_info {
          position: relative;
          text-align: center;

          .weight_input {
            width: 200rpx;
            height: 84rpx;
            margin: 0 auto;
            font-size: 60rpx;
            font-weight: 500;
            color: #1cd7ae;
            border-bottom: 4rpx solid #1cd7ae;
          }

          .unit {
            position: absolute;
            top: 0;
            right: 235rpx;
            font-size: 24rpx;
            font-weight: 500;
            color: #1cd7ae;
          }

          .hot {
            margin-top: 16rpx;
            font-size: 24rpx;
            font-weight: 400;
            color: #666;
          }
        }

        .submit {
          width: 100%;
          height: 88rpx;
          padding: 0 !important;
          margin: 76rpx 0 32rpx;
          font-size: 32rpx !important;
          font-weight: 500;
          line-height: 88rpx !important;
          color: #fff;
          background: #00d1b6;
          border-radius: 50rpx;
        }
      }

      .questionaire-info {
        padding: 0;
        overflow: hidden;
        .title {
          width: 100%;
          height: 108rpx;
          font-size: 30rpx;
          font-weight: 600;
          line-height: 108rpx;
          color: #222;
          text-align: center;
          border-bottom: 1rpx solid #e5e6eb;
        }

        .questionaire-list {
          padding: 32rpx;
          height: calc(100vh - 350rpx);
          overflow: hidden auto;

          .cell {
            box-sizing: border-box;
            display: flex;
            align-items: center;
            justify-content: space-between;
            height: 108rpx;
            background: #fafafa;
            border-radius: 16rpx;
            border: 1rpx solid #e5e6eb;
            margin-bottom: 24rpx;
            padding: 0 32rpx;

            .left {
              font-size: 30rpx;
              font-weight: 700;
              color: #222;
            }

            .right {
              display: flex;
              gap: 24rpx;
              justify-content: flex-end;
              font-size: 30rpx;
              font-weight: 400;
              color: #222;

              .form_input {
                text-align: right;
              }

              text {
                display: inline-block;
                width: 42rpx;
                text-align: left;
              }
            }
          }

          .user-item {
            height: 74rpx;
            background: #00d1b6;
            border-radius: 4rpx;
            .left {
              color: #fff;
            }
          }

          .topic_title {
            display: flex;
            align-items: center;
            margin-top: 40rpx;
            font-size: 32rpx;
            font-weight: 700;
            color: #222;
            justify-content: space-between;

            .tag {
              display: inline-block;
              padding: 4rpx 16rpx;
              margin-left: 8rpx;
              font-size: 24rpx;
              font-weight: 500;
              color: #fff;
              text-align: center;
              background: #5c8eff;
              border-radius: 4rpx;
            }

            .needlose {
              background: #ff813c;
            }
          }

          .search-input {
            display: flex;
            align-items: center;
            justify-content: flex-start;
            width: 100%;
            height: 84rpx;
            padding: 22rpx 24rpx;
            margin-top: 24rpx;
            font-size: 30rpx;
            font-weight: 400;
            line-height: 84rpx;
            color: #999;
            background: #fff;
            border: 2rpx solid #000;
            border-radius: 48rpx;
          }

          .allergy-foods {
            margin-top: 24rpx;

            .food-list {
              display: flex;
              flex-wrap: wrap;
              gap: 24rpx;
              justify-content: left;

              .foods-item {
                display: flex;
                align-items: center;
                height: 64rpx;
                padding: 0 16rpx;
                font-size: 28rpx;
                font-weight: 400;
                color: #00d1b6;
                background: rgb(0 209 182 / 10%);
                border-radius: 4rpx;
              }
            }
          }

          .topics {
            margin-top: 40rpx;

            .topic {
              width: 100%;
              height: 88rpx;
              padding-left: 32rpx;
              margin-bottom: 24rpx;
              font-size: 30rpx;
              font-weight: 400;
              line-height: 88rpx;
              text-align: left;
              background: #fafafa;
              border-radius: 8rpx;
            }

            .active {
              color: #00d1b6;
              background: rgb(0 209 182 / 5%);
              border: 1rpx solid #00d1b6;
            }

            .disabled {
              color: #ccc;
              background: #f5f5f5;
              border: 1rpx solid #e5e6eb;
            }
          }
        }
      }

      .submit-box {
        width: 100%;
        font-weight: 500;
        background: #ffffff;
        padding: 32rpx 24rpx;
        .submit-btn {
          width: 100%;
          height: 88rpx;
          background: #00d1b6;
          border-radius: 44rpx;
          color: #fff;
          font-weight: 600;
          font-size: 32rpx;
          text-align: center;
          line-height: 88rpx;
        }
      }

      // 加餐弹窗
      .lists {
        .item {
          height: 108rpx;
          font-size: 32rpx;
          font-weight: 400;
          line-height: 108rpx;
          color: #00d1b6;
          text-align: center;
          border-bottom: 1px solid #e5e6eb;
        }

        .item:last-child {
          border: none;
        }
      }

      .cancel {
        height: 108rpx;
        font-size: 32rpx;
        font-weight: 400;
        line-height: 108rpx;
        color: #222;
        text-align: center;
        border-top: 15rpx solid #f2f3f5;
      }

      .uni-calendar {
        .uni-calendar__header {
          .uni-calendar__header-text {
            font-size: 30rpx !important;
          }
        }

        .uni-calendar__box {
          .uni-calendar__weeks-day-text {
            font-size: 30rpx !important;
          }

          .uni-calendar-item__weeks-box-text {
            font-size: 30rpx !important;
          }

          .uni-calendar-item--isDay {
            border-radius: 8rpx;
          }
        }
      }
    }
  }

  .tab-icon {
    display: flex;
    align-items: center;
    margin-top: 8rpx;
  }

  ::v-deep .dialog-close {
    display: none;
  }

  ::v-deep .uni-calendar-item--isDay {
    background: #00d1b6;
  }

  ::v-deep .uni-calendar-item--checked {
    background: #00d1b6;
  }

  ::v-deep .uni-date-editor {
    width: 254rpx;
    margin: 0 auto;
  }

  ::v-deep .uni-calendar-item--isDay-text {
    color: #00d1b6;
  }

  ::v-deep .uni-calendar-item--isDay .uni-calendar-item--isDay-text {
    color: #fff;
  }

  ::v-deep .uni-calendar-item__weeks-box-circle {
    background: #00d1b6;
  }

  ::v-deep .uni-calendar-item__weeks-box .uni-calendar-item--checked {
    background-color: #00d1b6;
  }

  ::v-deep .uni-calendar__weeks-day {
    background: #ebfbf9;

    .uni-calendar__weeks-day-text {
      color: #00d1b6;
    }
  }

  ::v-deep .uni-datetime-picker--btn {
    height: 88rpx;
    line-height: 88rpx;
    background-color: #00d1b6;
  }

  ::v-deep .uni-progress-bar,
  ::v-deep .uni-progress-inner-bar {
    border-radius: 100rpx;
  }

  ::v-deep .u-icon__icon {
    top: 10rpx !important;
    font-size: 40rpx !important;
  }

  ::v-deep .search-input .u-icon__icon {
    top: 0 !important;
  }
}
</style>
